package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.response.EnterpricceIdVO;
import com.wing.cabinet.service.EnterpricceIdService;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.request.CabInventoryProductForm;
import com.wing.enterprise.product.model.response.ProductBrandVO;
import com.wing.product.dao.MostUsedKnifeListDao;
import com.wing.product.model.entity.*;
import com.wing.product.model.request.ProductDetailAttributeForm;
import com.wing.product.model.request.ProductDetailAttributeValueForm;
import com.wing.product.model.request.ProductDetailForm;
import com.wing.product.model.request.ProductForm;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.productself.model.entity.ProductDetailSelf;
import com.wing.productself.model.entity.ProductSelf;
import com.wing.productself.service.ProductDetailSelfService;
import com.wing.productself.service.ProductSelfService;
import com.wing.util.PulsarCommons;
import com.wing.util.PulsarUtils;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MostUsedKnifeListServiceImpl implements MostUsedKnifeListService {

    @Autowired
    private MostUsedKnifeListDao mostUsedKnifeListDao;

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryExtService productCategoryExtService;

    @Autowired
    private ProductDetailService productDetailService;

    //@Autowired
    //private ClientService clientService;

    @Autowired
    private ProductDetailAttributeService productDetailAttributeService;

    @Autowired
    private ProductDetailAttributeValueService productDetailAttributeValueService;

    @Autowired
    private EnterpricceIdService enterpricceIdService;

    @Autowired
    private EnterpriseClient enterpriseClient;

    @Autowired
    private ProductDetailSelfService productDetailSelfService;

    @Autowired
    private ProductSelfService productSelfService;

    @Autowired
    private ProductBrandService productBrandService;

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Value("${pulsar.client.topicUrl}")
    private String topicUrl;

    @Override
    public Page<ProductDetailVO> findAll(Page page, Map<String, Object> params) {
        List<ProductDetailVO> list = mostUsedKnifeListDao.findAll(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    @Transactional
    public void add(ProductForm productForm) throws Exception {
        EnterpricceIdVO enterpricceIdVO = enterpricceIdService.getEnterpricceIdVO();
        if (null == enterpricceIdVO) {
            throw new BusinessException("请先联系运维人员初始化企业基本信息!");
        }

        ProductBrandVO productBrandVO = enterpriseClient.getProductBrandById(productForm.getBrandId());
        if (null == productBrandVO) {
            throw new BusinessException("请选择正确的品牌!");
        }
        //添加产品
        JsonResult<List<com.wing.enterprise.product.model.entity.Product>> productList = enterpriseClient.getProductByCode(productForm.getProductCode());
        if (!productList.getData().isEmpty()) {
            throw new BusinessException("产品编码已存在！");
        }
//        //校验
        Product product = new Product();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(Product.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        product.setSettledCompanyId(Long.valueOf(enterpricceIdVO.getEnterpriseId()));
        BeanUtil.copyProperties(productForm, product, copyOptions);

        product.setBrandCode(productBrandVO.getCode());
        product.setBrandName(productBrandVO.getName());
        product.setProductCode(productForm.getProductCode());
        product.setDataSourceType(Product.DataSourceType.oneself);
        product.setCreator(JwtUtils.getLoginUserId());
        product.setCreatorName(JwtUtils.getLoginUsername());
        product.setType(Product.Type.knife);
        productService.save(product);

        //添加产品扩展属性
        if (StringUtils.isNotBlank(productForm.getProductCategoryExtId())) {
            String[] extArr = productForm.getProductCategoryExtId().split(",");
            List<ProductCategoryExt> extList = new ArrayList<ProductCategoryExt>();
            for (int i = 0; i < extArr.length; i++) {
                ProductCategoryExt extVo = new ProductCategoryExt();
                extVo.setProductId(product.getId());
                extVo.setCategoryId(Long.valueOf(extArr[i]));
                extList.add(extVo);
            }
            productCategoryExtService.saveBatch(extList);
        }

        //添加添加SKU
        List<ProductDetailForm> detailFormList = productForm.getProductDetailForm();
        List<ProductDetail> deatilList = new ArrayList<ProductDetail>();
        //判断SKU编号是否有重复
        List newList = detailFormList.stream().map(ProductDetailForm::getSkuCode).distinct().collect(Collectors.toList());
        if (newList.size() != detailFormList.size()) {
            throw new BusinessException("产品SKU编码重复！");
        }

        //判断商品条码是否有重复
        newList = detailFormList.stream().map(ProductDetailForm::getBarcode).distinct().collect(Collectors.toList());
        if (newList.size() != detailFormList.size()) {
            throw new BusinessException("商品条码重复！");
        }

        //判断商品规格是否有重复
        newList = detailFormList.stream().map(ProductDetailForm::getSkuSpecValue).distinct().collect(Collectors.toList());
        if (newList.size() != detailFormList.size()) {
            throw new BusinessException("商品规格重复！");
        }
        for (ProductDetailForm productDetailForm : detailFormList) {
            //监测skuCode是否存在，保证唯一
            // JsonResult<List<com.wing.enterprise.product.model.entity.ProductDetail>> skuCodeDetailList = enterpriseClient.getProductDetailByCompanyIdAndSkuCode(product.getSettledCompanyId(), productDetailForm.getSkuCode());
            List<ProductDetailSelf> productDetailList = productDetailSelfService.list(new LambdaQueryWrapper<ProductDetailSelf>()
                    .eq(ProductDetailSelf::getSettledCompanyId, product.getSettledCompanyId())
                    .eq(ProductDetailSelf::getSkuCode, productDetailForm.getSkuCode()));
            if (CollectionUtils.isNotEmpty(productDetailList)) {
                throw new BusinessException("产品SKU编码已存在！");
            }
            //监测商品条码是否存在，保证唯一
            //JsonResult<List<com.wing.enterprise.product.model.entity.ProductDetail>> barcodeDetailList = enterpriseClient.getProductDetailByBarcode(product.getSettledCompanyId(), productDetailForm.getBarcode());
            List<ProductDetailSelf> barcodeDetailList = productDetailSelfService.list(new LambdaQueryWrapper<ProductDetailSelf>()
                    .eq(ProductDetailSelf::getSettledCompanyId, product.getSettledCompanyId())
                    .eq(ProductDetailSelf::getBarcode, productDetailForm.getBarcode()));
            if (CollectionUtils.isNotEmpty(barcodeDetailList)) {
                throw new BusinessException("产品商品条码已存在！");
            }
            //监测商品规格值是否存在,保证唯一
            //JsonResult<List<com.wing.enterprise.product.model.entity.ProductDetail>> skuSpecValueDetailList = enterpriseClient.getProductDetailBySkuSpecValue(product.getId(),productDetailForm.getSkuSpecValue());
            List<ProductDetailSelf> skuSpecValueDetailList = productDetailSelfService.list(new LambdaQueryWrapper<ProductDetailSelf>()
                    .eq(ProductDetailSelf::getProductId, product.getId())
                    .eq(ProductDetailSelf::getSkuSpecValue, productDetailForm.getSkuSpecValue()));
            if (CollectionUtils.isNotEmpty(skuSpecValueDetailList)) {
                throw new BusinessException("产品商品规格已存在！");
            }
            ProductDetail productDetail = new ProductDetail();
            CopyOptions copySubOptions = CopyOptions.create()
                    .setEditable(ProductDetail.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(productDetailForm, productDetail, copySubOptions);
            productDetail.setProductId(product.getId());
            productDetail.setSettledCompanyId(Long.valueOf(enterpricceIdVO.getEnterpriseId()));
            productDetail.setSkuCode(productDetailForm.getSkuCode());
            productDetail.setProductTypeId(productForm.getProductTypeId());
            productDetail.setProductCategoryId(productForm.getProductCategoryId());
            productDetail.setUnitId(productForm.getUnitId());
            productDetail.setBrandId(productForm.getBrandId());
            productDetail.setProductPic(productForm.getPicture());
            productDetail.setInventoryUnitType(ProductDetail.InventoryUnitType.quantity);
            productDetail.setCreator(JwtUtils.getLoginUserId());
            productDetail.setRemark(productForm.getRemark());
            deatilList.add(productDetail);
            // 添加库存
            CabInventoryProductForm cabInventoryProduct = new CabInventoryProductForm();
            cabInventoryProduct.setSkuCode(productDetailForm.getSkuCode());
            cabInventoryProduct.setSkuType(1);
            enterpriseClient.addCabInventoryProduct(cabInventoryProduct);
        }
        productDetailService.saveBatch(deatilList);

        //添加产品属性
        if (null != productForm.getProductDetailAttributeForm() && productForm.getProductDetailAttributeForm().size() > 0) {
            for (ProductDetailAttributeForm productDetailAttributeForm : productForm.getProductDetailAttributeForm()) {
                ProductDetailAttribute productDetailAttribute = new ProductDetailAttribute();
                CopyOptions copySubOptions = CopyOptions.create()
                        .setEditable(ProductDetailAttribute.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(productDetailAttributeForm, productDetailAttribute, copySubOptions);
                productDetailAttribute.setProductId(product.getId());
                productDetailAttribute.setSettledCompanyId(Long.valueOf(enterpricceIdVO.getEnterpriseId()));
                productDetailAttributeService.save(productDetailAttribute);

                //添加属性值子表
                if (null == productDetailAttributeForm.getProductDetailAttributeValueForm() || productDetailAttributeForm.getProductDetailAttributeValueForm().size() < 0) {
                    continue;
                }

                List<ProductDetailAttributeValue> productDetailAttributeValueList = new ArrayList<ProductDetailAttributeValue>();
                for (ProductDetailAttributeValueForm productDetailAttributeValueForm : productDetailAttributeForm.getProductDetailAttributeValueForm()) {
                    ProductDetailAttributeValue productDetailAttributeValue = new ProductDetailAttributeValue();
                    CopyOptions copySubValueOptions = CopyOptions.create()
                            .setEditable(ProductDetailAttributeValue.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(productDetailAttributeValueForm, productDetailAttributeValue, copySubValueOptions);
                    productDetailAttributeValue.setProductId(product.getId());
                    productDetailAttributeValue.setSettledCompanyId(Long.valueOf(enterpricceIdVO.getEnterpriseId()));
                    productDetailAttributeValue.setProductAttrId(productDetailAttribute.getId());
                    productDetailAttributeValueList.add(productDetailAttributeValue);
                }
                productDetailAttributeValueService.saveBatch(productDetailAttributeValueList);
            }
        }
    }


    @Override
    public boolean removeById(Long id) {
        return mostUsedKnifeListDao.removeById(id);
    }

    @Override
    public boolean removeDetailById(Long id) {
        return mostUsedKnifeListDao.removeDetailById(id);
    }


    @Override
    public HashMap existById(Long productId) {
        return mostUsedKnifeListDao.existById(productId);
    }

    @Override
    public List<String> findAllDetailId() {
        return mostUsedKnifeListDao.findAllDetailId();
    }

    @Override
    public int countDetail(Long id) {
        return mostUsedKnifeListDao.countDetail(id);
    }

    @Override
    @Transactional
    public void deleteMostUsedKnifeList(String ids) throws Exception {
        String[] result = ids.split(",");
        for (int i = 0; i < result.length; i++) {
            Long skuId = Long.valueOf(result[i]);
            //删除pro_product_detail表记录
            Integer count = mostUsedKnifeListDao.countDetail(skuId);
            if (count == 1) {
                //删除pro_product表记录
                mostUsedKnifeListDao.removeById(skuId);
            }
            mostUsedKnifeListDao.removeDetailById(skuId);
            //删除库存表记录
            JsonResult jsonResult = enterpriseClient.inventoryDeleteBySkuId(skuId);
            if (null == jsonResult || jsonResult.getCode() != 200) {
                throw new BusinessException("删除库存表记录失败!");
            }

        }
    }


    @Override
    @Transactional
    public void saveSelfPickProduct(ProductForm productForm) {
        EnterpricceIdVO enterpricceIdVO = enterpricceIdService.getEnterpricceIdVO();
        if (null == enterpricceIdVO) {
            throw new BusinessException("请先联系运维人员初始化企业基本信息!");
        }
        if (StringUtils.isBlank(productForm.getProductCode())) {
            throw new BusinessException("产品编码不能为空!");
        }
        if (StringUtils.isBlank(productForm.getName())) {
            throw new BusinessException("产品名称不能为空!");
        }
        if (productForm.getProductTypeId() == null) {
            throw new BusinessException("产品类型不能为空!");
        }
        if (productForm.getProductCategoryId() == null) {
            throw new BusinessException("产品分类不能为空!");
        }
        com.wing.product.model.response.ProductBrandVO brandVO = new com.wing.product.model.response.ProductBrandVO();
        if (productForm.getBrandId() != null) {
            brandVO = productBrandService.get4appById(productForm.getBrandId());
            if (null == brandVO) {
                throw new BusinessException("请选择正确的品牌!");
            }
        }

        //添加产品
        List<ProductSelf> productSelfList = productSelfService.list(new LambdaQueryWrapper<ProductSelf>()
                .eq(ProductSelf::getProductCode, productForm.getProductCode()));
        if (CollectionUtils.isNotEmpty(productSelfList)) {
            throw new BusinessException("产品编码已存在！");
        }
        Product product = new Product();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(Product.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        product.setSettledCompanyId(Long.valueOf(enterpricceIdVO.getEnterpriseId()));
        BeanUtil.copyProperties(productForm, product, copyOptions);
        if (brandVO != null) {
            product.setBrandCode(brandVO.getCode());
            product.setBrandName(brandVO.getName());
        }
        product.setProductCode(productForm.getProductCode());
        product.setDataSourceType(Product.DataSourceType.oneself);
        product.setCreator(JwtUtils.getLoginUserId());
        product.setCreatorName(JwtUtils.getLoginUsername());
        product.setType(Product.Type.knife);
        productService.save(product);

        //添加添加SKU
        List<ProductDetailForm> detailFormList = productForm.getProductDetailForm();
        List<ProductDetail> deatilList = new ArrayList<ProductDetail>();
        //判断SKU编号是否有重复
       /* List newList = detailFormList.stream().map(ProductDetailForm::getSkuCode).distinct().collect(Collectors.toList());
        if (newList.size() != detailFormList.size()) {
            throw new BusinessException("产品SKU编码重复！");
        }*/
        for (ProductDetailForm productDetailForm : detailFormList) {
            ProductDetail skuCode = productDetailService.getOne(new QueryWrapper<ProductDetail>().eq("sku_code", productDetailForm.getSkuCode()));
            if(skuCode!=null){
                if(skuCode.getIsDeleted()){
                    productService.removeById(skuCode.getProductId());
                    productDetailService.removeById(skuCode.getId());
                }else {
                    throw new BusinessException("产品SKU编码重复！");
                }
            }

        }
        //判断商品规格是否有重复
        List newList = detailFormList.stream().map(ProductDetailForm::getSkuSpecValue).distinct().collect(Collectors.toList());
        if (newList.size() != detailFormList.size()) {
            throw new BusinessException("商品规格重复！");
        }
        for (ProductDetailForm productDetailForm : detailFormList) {
            //监测skuCode是否存在，保证唯一
            List<ProductDetailSelf> productDetailList = productDetailSelfService.list(new LambdaQueryWrapper<ProductDetailSelf>()
                    .eq(ProductDetailSelf::getSettledCompanyId, product.getSettledCompanyId())
                    .eq(ProductDetailSelf::getSkuCode, productDetailForm.getSkuCode()));
            if (CollectionUtils.isNotEmpty(productDetailList)) {
                throw new BusinessException("产品SKU编码已存在！");
            }
            if (StringUtils.isBlank(productDetailForm.getSkuCode())) {
                throw new BusinessException("产品SKU编码不能为空！");
            }
            if (productDetailForm.getMarketPrice() == null) {
                throw new BusinessException("市场价不能为空！");
            }
            if (StringUtils.isBlank(productDetailForm.getOldSpecCode())) {
                throw new BusinessException("原规格码不能为空！");
            }
            //监测商品规格值是否存在,保证唯一
            List<ProductDetailSelf> skuSpecValueDetailList = productDetailSelfService.list(new LambdaQueryWrapper<ProductDetailSelf>()
                    .eq(ProductDetailSelf::getProductId, product.getId())
                    .eq(ProductDetailSelf::getSkuSpecValue, productDetailForm.getSkuSpecValue()));
            if (CollectionUtils.isNotEmpty(skuSpecValueDetailList)) {
                throw new BusinessException("产品商品规格已存在！");
            }
            ProductDetail productDetail = new ProductDetail();
            CopyOptions copySubOptions = CopyOptions.create()
                    .setEditable(ProductDetail.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(productDetailForm, productDetail, copySubOptions);
            productDetail.setProductId(product.getId());
            productDetail.setSettledCompanyId(Long.valueOf(enterpricceIdVO.getEnterpriseId()));
            productDetail.setSkuCode(productDetailForm.getSkuCode());
            productDetail.setProductTypeId(productForm.getProductTypeId());
            productDetail.setProductCategoryId(productForm.getProductCategoryId());
            productDetail.setWarningQuantity(productForm.getWarningQuantity());
            if (StringUtils.isNotBlank(productForm.getPicture())) {
                productDetail.setProductPic(productForm.getPicture());
            }
            productDetail.setBrandId(productForm.getBrandId());
            productDetail.setInventoryUnitType(ProductDetail.InventoryUnitType.quantity);
            productDetail.setCreator(JwtUtils.getLoginUserId());
            deatilList.add(productDetail);
            // 添加库存
            CabInventoryProductForm cabInventoryProduct = new CabInventoryProductForm();
            cabInventoryProduct.setSkuCode(productDetailForm.getSkuCode());
            cabInventoryProduct.setSkuType(1);
            enterpriseClient.addCabInventoryProduct(cabInventoryProduct);
        }
        productDetailService.saveBatch(deatilList);
        String enterpriseCode = JwtUtils.getEnterpriseCode();
        sendMsg(product, detailFormList,enterpriseCode);
    }

    void sendMsg(Product product, List<ProductDetailForm> detailFormList, String enterpriseCode) {

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            syncDate(product, detailFormList,enterpriseCode);
                        } catch (Exception e) {
                            log.error("syn fail", e);
                        }
                    }
                });
            }
        });
    }

    // 数据同步
    private void syncDate(Product product, List<ProductDetailForm> detailFormList, String enterpriseCode) {

        // 同步自采产品 pro_product
        String uniqCode = enterpriseCode + "-" + product.getId();
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            product.setUniqCode(uniqCode);
            jsonObject.put("data", product);
            PulsarUtils.send(topicUrl + PulsarCommons.PRO_PRODUCT, jsonObject.toJSONString());
        } catch (Exception e) {
            log.error("sync err 同步pro_product失败 ", e);
            product.setIsSyns(0);
            productService.updateById(product);
        }

        // 同步自采产品 pro_product_detail
        if (detailFormList.size() > 0) {
            ProductDetail productDetail = null;
            try {
                for (ProductDetailForm productDetailForm : detailFormList) {
                    productDetail =  new ProductDetail();
                    CopyOptions copySubOptions = CopyOptions.create()
                            .setEditable(ProductDetail.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(productDetailForm, productDetail,copySubOptions);
                    productDetail.setSkuCode(enterpriseCode + "-" + productDetail.getSkuCode());
                    productDetail.setProductUniqCode(uniqCode);
                    productDetail.setProductTypeId(product.getProductTypeId());
                    productDetail.setProductCategoryId(product.getProductCategoryId());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "addOrUpdate");
                    jsonObject.put("data",productDetail);
                    PulsarUtils.send(topicUrl + PulsarCommons.PRO_PRODUCT_DETAIL, jsonObject.toJSONString());
                }
            } catch (Exception e) {
                log.error("sync err 同步pro_product失败 ", e);
//                productDetail.setIsSyns(ProductDetail.IsSyns.no);
//                productDetailService.updateById(productDetail);
                if(null != productDetail.getId()){
                    ProductDetail productDetailUpdate = new ProductDetail();
                    productDetailUpdate.setId(productDetail.getId());
                    productDetailUpdate.setIsSyns(ProductDetail.IsSyns.no);
                    productDetailService.updateById(productDetailUpdate);
                }
            }
        }

    }


    @Override
    @Transactional
    public void addLocalManualImport(List<ProductDetailForm> list) {
        for (int i = 0; i < list.size(); i++) {
            Product product = productService.getById(list.get(i).getProductId());
            if (product != null) {
                product.setIsLocalImport(Long.valueOf(1));
                productService.updateById(product);
            }
        }
    }

    @Override
    public boolean updateById(ProductDetail productDetail) {
        return productDetailService.updateById(productDetail);
    }

    @Override
    @Transactional
    public void addCompactProduct(ProductForm productForm) {
        EnterpricceIdVO enterpricceIdVO = enterpricceIdService.getEnterpricceIdVO();
        if (null == enterpricceIdVO) {
            throw new BusinessException("请先联系运维人员初始化企业基本信息!");
        }
        if (StringUtils.isBlank(productForm.getSkuCode())) {
            throw new BusinessException("SKU编码不能为空!");
        }
        if (StringUtils.isBlank(productForm.getName())) {
            throw new BusinessException("产品名称不能为空!");
        }
        if (productForm.getProductTypeId() == null) {
            throw new BusinessException("产品类型不能为空!");
        }
        if (productForm.getProductCategoryId() == null) {
            throw new BusinessException("产品分类不能为空!");
        }
        if (productForm.getBasePrice() == null) {
            throw new BusinessException("产品基础单价不能为空!");
        }
        com.wing.product.model.response.ProductBrandVO brandVO = new com.wing.product.model.response.ProductBrandVO();
        if (productForm.getBrandId() != 0){
            if (productForm.getBrandId() != null) {
                brandVO = productBrandService.get4appById(productForm.getBrandId());
                if (null == brandVO) {
                    throw new BusinessException("请选择正确的品牌!");
                }
            }
        }


        //监测skuCode是否存在，保证唯一
        List<ProductDetailSelf> productDetailList = productDetailSelfService.list(new LambdaQueryWrapper<ProductDetailSelf>()
                .eq(ProductDetailSelf::getSettledCompanyId, enterpricceIdVO.getEnterpriseId())
                .eq(ProductDetailSelf::getSkuCode, productForm.getSkuCode()));

        Long productId = productForm.getProductId();
        if(null == productId){
            //生成产品编码
            String questionNum = "CP-" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + (int) (Math.random() * 1000);
            //添加产品
            Product product = new Product();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(Product.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(productForm, product, copyOptions);
            if (brandVO != null) {
                product.setBrandCode(brandVO.getCode());
                product.setBrandName(brandVO.getName());
            }
            product.setSettledCompanyId(Long.valueOf(enterpricceIdVO.getEnterpriseId()));
            product.setProductCode(questionNum);
            product.setDataSourceType(Product.DataSourceType.oneself);
            product.setCreator(JwtUtils.getLoginUserId());
            product.setCreatorName(JwtUtils.getLoginUsername());
            product.setType(Product.Type.knife);
            product.setDataSourceType(Product.DataSourceType.oneself);
            productService.save(product);
            productId = product.getId();

            if (CollectionUtils.isNotEmpty(productDetailList)) {
                if(!productDetailList.get(0).getIsDeleted()){
                    throw new BusinessException("产品SKU编码已存在！");
                }else {
                    productDetailSelfService.removeById(productDetailList.get(0).getId());
                    productService.removeById(productDetailList.get(0).getProductId());
                }
            }
        }else{
            if (CollectionUtils.isNotEmpty(productDetailList)) {
                if(!productDetailList.get(0).getIsDeleted()){
                    throw new BusinessException("产品SKU编码已存在！");
                }else {
                    productDetailSelfService.removeById(productDetailList.get(0).getId());
                }
            }
        }

        //添加SKU
        ProductDetail productDetail = new ProductDetail();
        productDetail.setProductId(productId);
        productDetail.setSkuCode(productForm.getSkuCode());
        productDetail.setSkuName(productForm.getName());
        productDetail.setSkuSpecValueNames(productForm.getSkuSpecValueNames());
        productDetail.setOldSpecCode(productForm.getSkuSpecValueNames());
        productDetail.setMarketPrice(productForm.getMarketPrice());
        productDetail.setSettledCompanyId(Long.valueOf(enterpricceIdVO.getEnterpriseId()));
        productDetail.setProductTypeId(productForm.getProductTypeId());
        productDetail.setProductCategoryId(productForm.getProductCategoryId());
        productDetail.setBrandId(productForm.getBrandId());
        productDetail.setLifeSpan(productForm.getLifeSpan());
        productDetail.setWarningQuantity(productForm.getWarningQuantity());
        productDetail.setSimplify(1);
        productDetail.setUnitId(productForm.getUnitId());
        productDetail.setRemark(productForm.getRemark());
        productDetail.setBasePrice(productForm.getBasePrice());
        if(StringUtils.isNotBlank(productForm.getLifeUnit())){
            if (productForm.getLifeUnit().equals("minute")) {
                productDetail.setLifeUnit(ProductDetail.LifeUnit.minute);
            } else if (productForm.getLifeUnit().equals("number")) {
                productDetail.setLifeUnit(ProductDetail.LifeUnit.number);
            }
        }
        if(StringUtils.isNotBlank(productForm.getInventoryUnitType())){
            if (productForm.getInventoryUnitType().equals("weight")) {
                productDetail.setInventoryUnitType(ProductDetail.InventoryUnitType.weight);
            } else if (productForm.getInventoryUnitType().equals("quantity")) {
                productDetail.setInventoryUnitType(ProductDetail.InventoryUnitType.quantity);
            }
        }
//        if (productForm.getStorageKnifeType().equals("storage")) {
//            productDetail.setStorageKnifeType(ProductDetail.StorageKnifeType.storage);
//        } else if (productForm.getStorageKnifeType().equals("scraper")) {
//            productDetail.setStorageKnifeType(ProductDetail.StorageKnifeType.scraper);
//        }
        productDetail.setReturnType(productForm.getReturnType());
        productDetail.setProductPic(productForm.getPicture());
        productDetail.setCreator(JwtUtils.getLoginUserId());
        if(productForm.getSupplierId()!=null){
            productDetail.setSupplierId(productForm.getSupplierId());
        }
        if(productForm.getPackId()!=null){
            productDetail.setPackId(productForm.getPackId());
        }
        if(productForm.getReturnThreshold()!=null){
            productDetail.setReturnThreshold(productForm.getReturnThreshold());
        }
        if(productForm.getLethargyThreshold()!=null){
            productDetail.setLethargyThreshold(productForm.getLethargyThreshold());
        }
        productDetailService.save(productDetail);
    }

    @Override
    public void updateCompactProduct(ProductForm productForm) {
        LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
        ProductDetail productDetail = productDetailService.getById(productForm.getId());
        if (productDetail.getProductId() != null) {
            Long productId = productForm.getProductId();
            if(null == productId){
                Product product = new Product();
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(Product.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(productForm, product, copyOptions);
                product.setId(productDetail.getProductId());
                productService.updateById(product);
                if(productForm.getUnitId()==null){
                    updateWrapper.set(Product::getUnitId,null);
                    updateWrapper.eq(Product::getId,productDetail.getProductId());
                    productService.update(updateWrapper);
                    productDetail.setUnitId(null);
                }
            }else{
                if(productForm.getUnitId()==null){
                    productDetail.setUnitId(null);
                }
                productDetail.setProductId(productId);
            }
            productDetail.setSkuName(productForm.getName());
            productDetail.setSkuSpecValueNames(productForm.getSkuSpecValueNames());
            productDetail.setOldSpecCode(productForm.getSkuSpecValueNames());
            productDetail.setMarketPrice(productForm.getMarketPrice());
            if(productForm.getBasePrice() != null){
                productDetail.setBasePrice(productForm.getBasePrice());
            }
            productDetail.setProductTypeId(productForm.getProductTypeId());
            productDetail.setProductCategoryId(productForm.getProductCategoryId());
            productDetail.setBrandId(productForm.getBrandId());
            productDetail.setLifeSpan(productForm.getLifeSpan());
            productDetail.setWarningQuantity(productForm.getWarningQuantity());
            if(StringUtils.isNotBlank(productForm.getLifeUnit())){
                if (productForm.getLifeUnit().equals("minute")) {
                    productDetail.setLifeUnit(ProductDetail.LifeUnit.minute);
                } else if (productForm.getLifeUnit().equals("number")) {
                    productDetail.setLifeUnit(ProductDetail.LifeUnit.number);
                }
            }
            if(StringUtils.isNotBlank(productForm.getInventoryUnitType())){
                if (productForm.getInventoryUnitType().equals("weight")) {
                    productDetail.setInventoryUnitType(ProductDetail.InventoryUnitType.weight);
                } else if (productForm.getInventoryUnitType().equals("quantity")) {
                    productDetail.setInventoryUnitType(ProductDetail.InventoryUnitType.quantity);
                }
            }
//            if (productForm.getStorageKnifeType().equals("storage")) {
//                productDetail.setStorageKnifeType(ProductDetail.StorageKnifeType.storage);
//            } else if (productForm.getStorageKnifeType().equals("scraper")) {
//                productDetail.setStorageKnifeType(ProductDetail.StorageKnifeType.scraper);
//            }
            if(productForm.getSupplierId()!=null){
                productDetail.setSupplierId(productForm.getSupplierId());
            }
            if(productForm.getPackId()!=null){
                productDetail.setUnitId(productForm.getUnitId());
            }
            if(productForm.getPackId()!=null){
                productDetail.setPackId(productForm.getPackId());
            }
            if(productForm.getReturnThreshold()!=null){
                productDetail.setReturnThreshold(productForm.getReturnThreshold());
            }
            if(productForm.getLethargyThreshold()!=null){
                productDetail.setLethargyThreshold(productForm.getLethargyThreshold());
            }
            productDetail.setReturnType(productForm.getReturnType());
            productDetail.setProductPic(productForm.getPicture());
            productDetailService.updateById(productDetail);
        }
    }

    @Override
    public JsonResult isOnlyCode(String code, Long id) {
        QueryWrapper<ProductDetail> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(code)){
            queryWrapper.eq("sku_code", code);
        }
        if (id!=null) {
            queryWrapper.ne("id", id);
        }
        int count = productDetailService.count(queryWrapper);
        return JsonResult.success(count==0);
    }

    @Override
    public Page<ProductDetailVO> findAllCancellationMaterial(Page page, Map<String, Object> params) {
        List<ProductDetailVO> list = mostUsedKnifeListDao.findAllCancellationMaterial(page, params);
        page.setRecords(list);
        return page;
    }

}
